<template>
	<jiess :setup="setup" />
</template>

<style lang="scss">
	.captcha {
		height: 40px;
		cursor: pointer;
		margin-left: 6px;
		border-radius: 4px;
		border: 1px solid #ddd;
	}

	.captcha>svg {
		height: 38px;
		width: 108px;
	}
</style>

<script setup>
	import tokenCookie from '@/assets/utils/cookies/token';
	import { ElDivider, ElButton } from 'element-plus';
	import { userInfoApi } from '@/services/api-common';
	import { useRouter } from 'vue-router';
	const router = useRouter();

	function setup() {
		const captchaData = $ref({});
		const loadingSure = $ref(false);
		const area = this.area({
			header: '登录管理系统',
			span: 24,
			initialValues: {
				loginName: 'admin',
				password: '123456'
			}
		});
		const buildCaptcha = () => {
			userInfoApi.captcha().then(dd => {
				captchaData.value = dd;
			});
		};
		// 初始化构建验证码
		buildCaptcha();
		area.add(
			$Input({
				$name: 'loginName',
				$label: '账号',
				size: 'large',
				$formItemParam: { labelWidth: '48px' },
				$rules: [val => { if (!val) return '请输入账号' }]
			}),
			$Input({
				$name: 'password',
				$label: '密码',
				size: 'large',
				type: 'password',
				showPassword: true,
				$formItemParam: { labelWidth: '48px' },
				$rules: [val => { if (!val) return '请输入密码' }]
			}),
			$Input({
				$name: 'captcha',
				$label: '验证码',
				size: 'large',
				placeholder: '请输入验证码',
				$formItemParam: { labelWidth: '62px' },
				$brother: [{
					children: {
						is: 'img',
						class: 'captcha',
						onClick: buildCaptcha,
						src: {
							$proxy: captchaData,
							done: dd => dd.data
						},
						style: {
							'width': '100px',
							'vertical-align': 'bottom'
						}
					}
				}],
				$rules: [val => {
					if (val) {
						let { text } = captchaData.value;
						text = text.toLocaleUpperCase();
						val = val.toLocaleUpperCase();
						if (text !== val) return '验证码有误';
					} else {
						return '请输入验证码';
					}
				}]
			}),
		);
		area.add({ is: ElDivider, style: { margin: '12px 0 24px 0' } }, {
			is: ElButton,
			size: 'large',
			class: 'w-full',
			children: '重置',
			style: { width: 'calc(50% - 6px)' },
			onClick: () => action.resetFields()
		}, {
			is: ElButton,
			type: 'primary',
			size: 'large',
			children: '登录',
			loading: { $proxy: loadingSure },
			style: { width: 'calc(50% - 6px)' },
			onClick: async () => {
				const values = await action.validateFields();
				const data = await userInfoApi.login(values);
				loadingSure.value = true;
				localStorage.userData = JSON.stringify(data);
				tokenCookie.set(data.accessToken);
				loadingSure.value = false;
				router.push('/');
			}
		});
		const action = area.done();
	}
</script>